package com.lingtong.common.exception;

import com.lingtong.common.result.Result;
import com.lingtong.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.logging.Logger;


/**
 * @author 孙灵通【sunlingtong@cyou-inc.com】
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理
 * @create 2021-03-19 16:26
 */

//@ControllerAdvice，是Spring3.2提供的新注解,它是一个Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {



//    @ExceptionHandler(value = HystrixRuntimeException.class)
//    @ResponseStatus(HttpStatus.OK)
//    public Object hystrixRuntimeExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
//        log.error(ResultCodeEnum.SERVICE_ERROR.getMessage(), exception);
//        return Result.build(null,ResultCodeEnum.SERVICE_ERROR);
//    }

    /**
     * 自定义异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result error(ServiceException e){
        log.error(e.getLogMessage());
        return Result.build(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        log.error(ResultCodeEnum.FAIL.getMessage(),e);
        return  Result.fail();
    }

}
